package com.yfjin.fbus;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;


import com.google.gson.Gson;
import com.yfjin.fbus.annotion.ClassId;
import com.yfjin.fbus.request.RequestBean;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

public class NameServerManager extends Service {


    public static final int PORT = 10086;
    public static final int TYPE_GET = 1;
    public static final int TYPE_INVOCATION = 2;

    private static final Gson GSON = new Gson();

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    private Map<String, WebSocket> mServerMap = new HashMap<>();


    private ProjectSocketServer mProjectServer;


    @Override
    public void onCreate() {
        super.onCreate();
        mProjectServer = new ProjectSocketServer(PORT);
        mProjectServer.start();
        new Thread(() -> {
            mProjectServer = new ProjectSocketServer(PORT);
            mProjectServer.start();
        }).start();
    }


    class ProjectSocketServer extends WebSocketServer {

        public ProjectSocketServer(int port) {
            super(new InetSocketAddress(port));
        }

        @Override
        public void onOpen(WebSocket conn, ClientHandshake handshake) {

            Log.i("123123", "server:onOpen" );

            mServerMap.put(conn.getRemoteSocketAddress().getAddress().getHostAddress(), conn);
        }

        @Override
        public void onClose(WebSocket conn, int code, String reason, boolean remote) {
            mServerMap.remove(conn.getRemoteSocketAddress().getAddress().getHostAddress());
        }


        @Override
        public void onMessage(WebSocket conn, String message) {

        }

        @Override
        public void onMessage(WebSocket conn, ByteBuffer message) {
            super.onMessage(conn, message);
            byte[] buf = new byte[message.remaining()];
            message.get(buf);

            String data = new String(buf);
            Log.i("123123", "data:" + data);

            dealRequest(data);
        }

        @Override
        public void onError(WebSocket conn, Exception ex) {

        }

        @Override
        public void onStart() {

        }
    }


    private String dealRequest(String request) {
        RequestBean b = GSON.fromJson(request, RequestBean.class);
        int type = b.getType();
        switch (type) {
            case TYPE_GET:
                Method method = IpcNameManager.getDefault().getNameCenter().getMethod(b);
                Object[] parameters = makeParameterObject(b);


                try {
                    Object object = method.invoke(null, parameters);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                }

                break;

            case TYPE_INVOCATION:
                break;

            default:
                break;
        }


        return null;
    }

    private Object[] makeParameterObject(RequestBean request) {
        Object[] parameters = null;
        RequestBean.RequestParamter[] requestParamters = request.getRequestParamters();
        if (requestParamters != null && requestParamters.length > 0) {
            parameters = new Object[requestParamters.length];

            for (int i = 0; i < requestParamters.length; i++) {
                RequestBean.RequestParamter rp = requestParamters[i];
                Class<?> clazz = IpcNameManager.getDefault().getNameCenter().getClassType(rp.getParameterClassName());

                parameters[i] = GSON.fromJson(rp.getParameterValue(), clazz);
            }
        } else {
            parameters = new Object[0];
        }

        return parameters;
    }
}
